<template>
  <div class="app-container">
    <el-form
      :model="queryData"
      ref="searchFormRef"
      :inline="true"
      label-width="85px"
      class="globalSerchFormStyle"
    >
      <el-row>
        <el-col :span="6" v-if="authUser">
          <el-form-item label="油企名称" prop="enterpriseId" size="small">
            <el-select
              style="width: 180px"
              v-model="queryData.enterpriseId"
              :clearable="true"
              filterable
              placeholder="请选择油企"
              @change="handleSelectChange"
            >
              <el-option
                v-for="(item, index) in enterpriseList"
                :key="index"
                :value="item.enterpriseId"
                :label="item.enterpriseName"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="油站名称" prop="stationId" size="small">
            <el-select
              style="width: 180px"
              v-model="queryData.stationId"
              :clearable="true"
              filterable
              placeholder="请选择油站名称"
            >
              <el-option
                v-for="item in stationList"
                :key="item.stationId"
                :label="item.stationName"
                :value="item.stationId"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="电子卡类型" prop="cardType">
            <el-select
              style="width: 180px"
              v-model="queryData.cardType"
              :clearable="true"
              filterable
              placeholder="请选择电子卡"
            >
              <el-option
                v-for="item in cardTypeList"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6" v-if="!authUser">
          <el-form-item label="活动状态" prop="status">
            <el-select
              style="width: 180px"
              v-model="queryData.status"
              :clearable="true"
              filterable
              placeholder="请选择活动状态"
            >
              <el-option
                v-for="item in statusList"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <div v-show="collapse">
        <el-row>
          <el-col :span="6" v-if="authUser">
            <el-form-item label="活动状态" prop="status">
              <el-select
                style="width: 180px"
                v-model="queryData.status"
                :clearable="true"
                filterable
                placeholder="请选择活动状态"
              >
                <el-option
                  v-for="item in statusList"
                  :key="item.label"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="创建时间" prop="createdDate" size="small">
              <el-date-picker
                size="small"
                v-model="dateRangeCreatedDate"
                value-format="yyyy-MM-dd HH:mm:ss"
                type="datetimerange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                style="width: 180px"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </div>
    </el-form>

    <el-row
      :gutter="10"
      style="
        border-top: none;
        border-bottom: 1px solid #f5f5f5;
        padding: 15px 0px;
        margin-top: 10px;
      "
    >
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          plain
          size="mini"
          id="closeSearchBtn"
          @click="
            (closeSearch) => {
              collapse = !collapse;
            }
          "
        >
          {{ collapse ? "收起" : "展开更多" }}
          <i :class="collapse ? 'el-icon-arrow-up ' : 'el-icon-arrow-down'"></i>
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          size="mini"
          :disabled="selectionList.length < 1"
          @click="handleUpdateStaus('FREEZE')"
          >冻结</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          size="mini"
          icon="el-icon-delete"
          :disabled="selectionList.length < 1"
          @click="handleDelAll"
          >删除</el-button
        >
      </el-col>
    </el-row>

    <el-table
      :data="oilList"
      v-loading="loading"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55"> </el-table-column>
      <el-table-column
        v-if="authUser"
        prop="enterpriseName"
        label="油企名称"
        show-overflow-tooltip
        width="200"
      />
      <el-table-column
        prop="stationName"
        label="油站名称"
        show-overflow-tooltip
        width="200"
      />cardType
      <el-table-column label="活动形式" show-overflow-tooltip width="150">
        <template slot-scope="scope">
          {{ scope.row.activityMode === "recharge" ? "充值" : "" }}
          {{ scope.row.activityMode === "consume" ? "消费" : "" }}
        </template>
      </el-table-column>
      <el-table-column
        prop="cardType"
        label="电子卡类型"
        show-overflow-tooltip
        width="200"
      >
        <template slot-scope="scope">
          {{ scope.row.cardType.includes("1") ? "汽油卡," : "" }}
          {{ scope.row.cardType.includes("2") ? "柴油卡," : "" }}
          {{ scope.row.cardType.includes("3") ? "非油品," : "" }}
          {{ scope.row.cardType.includes("4") ? "LNG," : "" }}
          {{ scope.row.cardType.includes("5") ? "CNG," : "" }}
          {{ scope.row.cardType.includes("0") ? "通用卡," : "" }}
        </template></el-table-column
      >
      <el-table-column
        prop="status"
        label="状态"
        show-overflow-tooltip
        width="150"
      >
        <template v-slot="{ row }">
          <span
            v-if="row.status === 'NORMAL'"
            style="color: black; letter-spacing: 15px"
            >正常</span
          >
          <span v-if="row.status === 'FREEZE'" style="color: lightgray"
            >冻结</span
          >
          <span v-if="row.status === 'STOP'" style="color: red">已停止</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="activityType"
        label="活动类型"
        show-overflow-tooltip
        width="150"
        :formatter="activityTypeFormatter"
      />
      <el-table-column
        prop="createTime"
        label="创建时间"
        show-overflow-tooltip
        width="200"
      />
      <af-table-column
        label="操作"
        align="left"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            type="text"
            size="mini"
            style="margin: 0px 5px"
            @click="handleView(scope.row)"
            >查看</el-button
          >
          <el-button
            type="text"
            size="mini"
            style="margin: 0px 5px; color: black"
            v-show="scope.row.status === 'FREEZE'"
            @click="handleUpdateStaus('STOP', scope.row)"
            >解冻</el-button
          >
          <el-button
            type="text"
            size="mini"
            style="margin: 0px 5px; color: #e6a23c"
            v-show="scope.row.status === 'STOP'"
            @click="handleUpdateStaus('NORMAL', scope.row)"
            >重启</el-button
          >
          <el-button
            type="text"
            size="mini"
            style="margin: 0px 5px; color: red"
            v-show="scope.row.status === 'NORMAL'"
            @click="handleUpdateStaus('STOP', scope.row)"
            >停止</el-button
          >
        </template>
      </af-table-column>
    </el-table>

    <el-pagination
      class="fr"
      style="margin-top: 8px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="page"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <dzkRuleForm
      ref="dzkRuleForm"
      :parm="params"
      @getData="getData"
      id="drawer"
    />
  </div>
</template>

<script>
import { listEnterpriseStation } from "@/api/dept";
import { enterpriseList } from "@/api/station/order";
import {
  detailList,
  deleteDetails,
  updateStatus,
  detailGetInfo,
} from "@/api/customer/cardSetting";
import dzkRuleForm from "./dzk-rule-form.vue";
import { creationList } from "@/api/coupon/creation";

export default {
  components: { dzkRuleForm },
  data() {
    return {
      // 查询参数
      queryData: {
        cardType: null,
        status: null,
        stationId: null,
      },
      page: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      oilList: [],
      collapse: false,
      enterpriseList: [],
      stationList: [],
      dateRangeCreatedDate: [],
      cardTypeList: [
        {
          label: "通用卡",
          value: 0,
        },
        {
          label: "汽油",
          value: 1,
        },
        {
          label: "柴油",
          value: 2,
        },
        {
          label: "非油品",
          value: 3,
        },
        {
          label: "LNG",
          value: 4,
        },
        {
          label: "CNG",
          value: 5,
        },
      ],
      statusList: [
        {
          label: "正常",
          value: "NORMAL",
        },
        {
          label: "冻结中",
          value: "FREEZE",
        },
        {
          label: "已停止",
          value: "STOP",
        },
      ],
      selectionList: [],
      params: {},
    };
  },
  created() {
    this.getData();
    this.getEnterpriseList();
    // 如果当前是油企账号，则获取该企业下的油站
    if (this.presentEnterprise && this.presentEnterprise.enterpriseId) {
      this.getStationList(this.presentEnterprise.enterpriseId);
    }
  },
  methods: {
    // 查看
    async handleView(row) {
      let res = await detailGetInfo(row.id);
      let creationRes = await creationList({ status: 1 });
      if (res && res.data) {
        if (res.data.activityType === "coupon") {
          for (let i = 0; i < res.data.contentList.length; i++) {
            for (
              let j = 0;
              j < res.data.contentList[i].couponIssueId.length;
              j++
            ) {
              res.data.contentList[i].couponIssueId[j] =
                res.data.contentList[i].couponIssueId[j] + "";
            }
          }
        }
        //  res.data.cardType = parseInt(res.data.cardType);
      }
      console.log("查看电子卡数据：", res);
      this.params = {
        drawerShow: true,
        drawerType: "view",
        ruleData: res.data || {},
        settingData: {
          enterpriseList: this.enterpriseList,
          stationList: this.stationList,
          cardTypeList: this.cardTypeList,
          couponList: creationRes.rows || [],
        },
      };
      this.$nextTick(() => {
        let drawer = document.getElementById("drawer");
        let drawerDiv = drawer.getElementsByTagName("section")[0];
        drawerDiv.scrollTop = 0;
      });
    },
    // 新增
    async handleAdd() {
      let res = await creationList({ status: 1 });
      this.params = {
        drawerShow: true,
        drawerType: "new",
        ruleData: {
          contentList: [{}],
          sendFlag: 1,
        },
        settingData: {
          enterpriseList: this.enterpriseList,
          stationList: this.stationList,
          cardTypeList: this.cardTypeList,
          couponList: res.rows || [],
        },
      };
      this.$nextTick(() => {
        let drawer = document.getElementById("drawer");
        let drawerDiv = drawer.getElementsByTagName("section")[0];
        drawerDiv.scrollTop = 0;
      });
    },
    // 修改状态
    handleUpdateStaus(key, row = null) {
      console.log(this.selectionList);
      this.$confirm(`确认更新勾选的活动状态吗？`).then(() => {
        let ids = [];
        if (row) {
          ids.push(row.id);
        } else {
          ids = this.selectionList.map((item) => item.id);
        }
        updateStatus(key, ids).then((res) => {
          if (res && res.code === 200) {
            this.$message.success(res.msg);
            this.selectionList = [];
            this.getData();
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    // 批量删除
    handleDelAll() {
      console.log(this.selectionList);
      this.$confirm(`确认删除勾选的活动吗？`).then(() => {
        let ids = this.selectionList.map((item) => item.id);
        deleteDetails(ids).then((res) => {
          if (res && res.code === 200) {
            this.$message.success(res.msg);
            this.selectionList = [];
            this.getData();
          } else {
            this.$message.error(res.msg);
          }
        });
      });
    },
    // 根据油企获取油站
    handleSelectChange(value) {
      this.stationList = [];
      this.queryData.stationId = null;
      this.getStationList(value);
    },
    // 查询油企
    getEnterpriseList() {
      enterpriseList().then((res) => {
        this.enterpriseList = res.rows;
      });
    },
    getStationList(val) {
      listEnterpriseStation({ enterpriseId: val }).then((res) => {
        this.stationList = res;
      });
    },
    handleSelectionChange(selection) {
      this.selectionList = selection;
    },
    cardTypeFormatter(row, column) {
      const types = {
        0: "通用",
        1: "汽油卡",
        2: "柴油卡",
        3: "非油品",
        4: "LNG",
        5: "CNG",
      };
      return types[row.cardType];
    },
    activityTypeFormatter(row) {
      const types = {
        balance: "赠送电子卡金额",
        coupon: "赠送优惠券",
        integral: "赠送积分",
      };
      return types[row.activityType];
    },
    getData() {
      if (this.loading) return;
      this.loading = true;
      this.addDateRange(this.queryData, this.dateRangeCreatedDate);
      let queryData = this.getQueryData(this.queryData);
      queryData = Object.assign(
        {
          pageNum: this.page,
          pageSize: this.pageSize,
        },
        queryData
      );
      detailList(queryData).then((res) => {
        console.log(12345, res);
        if (res && res.code === 200) {
          this.oilList = res.rows;
          this.total = res.total;
        } else {
          this.oilList = [];
          this.total = 0;
        }
      });
      this.loading = false;
    },
    handleSizeChange(size) {
      this.pageSize = size;
      this.getData();
    },
    handleCurrentChange(page) {
      this.page = page;
      this.getData();
    },
    handleQuery() {
      this.getData();
    },
    resetQuery() {
      this.$refs["searchFormRef"].resetFields();
      this.dateRangeCreatedDate = [];
      this.getData();
    },
    getQueryData(data) {
      let queryData = data;
      Object.keys(queryData).forEach((key) => {
        if (queryData[key] === "" || queryData[key] === undefined) {
          queryData[key] = null;
        }
      });
      return queryData;
    },
  },
  computed: {
    authUser() {
      let roles = this.$store.state.user.roles;
      if (roles.includes("admin")) {
        return true;
      } else {
        return false;
      }
    },
  },
};
</script>
<style lang="scss">
.card-table {
  margin-top: 40px;
  background-color: #f8f8f8;

  .el-button {
    margin-bottom: 20px;
    margin-right: 20px;
  }
}

::v-deep .el-form-item {
  .el-form-item__label {
    padding: 0;
    margin: 0;
  }

  .el-button--cyan {
    margin-left: 20px;
  }
}
</style>
